package com.sky.d_thread;

/**
 * wait AND notify
 * @Author:hjt
 */
public class WNDemo {
	final static Object object = new Object();
	
	public static class T1 extends Thread{

		@Override
		public void run() {
			synchronized (object) {
				
				System.out.println(System.currentTimeMillis() + ":T1 start");
				try {
					
					//T1线程等待获取object对象锁
					System.out.println(System.currentTimeMillis() + ":T1 wait object");
					//这个方法的调用必须在synchronized (object)里面，否则会有问题
					//需要拿到object的对象锁
					object.wait();
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				System.out.println(System.currentTimeMillis() + ":T1 end");
			}
		}
	}
	
	public static class T2 extends Thread{

		@Override
		public void run() {
			synchronized (object) {
				
				System.out.println(System.currentTimeMillis() + ":T2 start");
				
				//需要拿到object的对象锁
				//唤醒一个线程
				object.notify();
				
				System.out.println(System.currentTimeMillis() + ":T2 end");
				try {
					Thread.sleep(1000);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	public static void main(String[] args) {
		Thread t1 = new T1();
		Thread t2 = new T2();
		
		t1.start();
		t2.start();
	}
	
	/**
	 object 调用wait之后，会在等待队列之中
	 当调用notify之后会随机唤醒等待队列中的一个，调用notifyAll会唤醒队列中所有的等待线程 
	 */
}
